//
//  CustomGgThirdView.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/28.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "CustomGgThirdView.h"

#import "FenLeiExistListModle.h"
#import "FenLeiSelectListModle.h"


@interface CustomGgThirdView ()<UITextFieldDelegate>

@property (nonatomic, assign) NSInteger countGuige;//规格的数量 即section个数
@property (nonatomic, strong) NSString *priceOne;//单价

@property (nonatomic, strong) NSString *minNum;//购买最小数量限制
@property (nonatomic, strong) NSString *maxNum;//购买库存量限制
@property (nonatomic, strong)NSString *maxNumTemp;//最大购买数量


@property (nonatomic, strong) UILabel *countMoenyLable;

@end

@implementation CustomGgThirdView
{
    UIView *bgv;
    UIView *countView;
    
    UITextField *tf_count;
    NSInteger numPay;
    
    
    CGFloat  changeHight;//视图的高
    CGFloat  changeHight2;//logo的高
    
    
    NSMutableArray *btnTotalArray;//存储视图所有btn
    NSMutableArray *selectArray;//存储选中btn 的文字
    
    
    
}

-(void)setTotalArray:(NSMutableArray *)totalArray{
    
    _totalArray = totalArray;
    
    //    if (_totalArray.count) {
    [self getDataAndUI];
    
    //    }
    
}

-(void)getDataAndUI{
    
    _minNum = _selectModle.minimum;
    _maxNum = _selectModle.store_nums;//库存量
    _priceOne = _selectModle.sell_price;
    _maxNumTemp = _selectModle.maximum;//最大购买数量
    
    [selectArray addObjectsFromArray:_selectModle.sku_key];
    
    
    _countGuige = selectArray.count;
    
    
    CGFloat selfView_height = 90*self.totalArray.count + 65+20 + 50 + 80;
    
    changeHight = 90*self.totalArray.count + 65+20 + 50 + 80;
    
    //弹起：
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    //回收：
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    _tempArray1 = [NSMutableArray array];
    _tempArray2 = [NSMutableArray array];
    
    bgv = [[UIView alloc] initWithFrame:CGRectMake(0, kView_Height - selfView_height, kView_Width, selfView_height)];
    bgv.backgroundColor = [UIColor whiteColor];
    [self addSubview:bgv];
    [self configureView];
    [self addTitleStrArray];
    
    [self addCountView];
    
    // 处理后续 选中
    [self handleData];
    
}


- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        btnTotalArray = [NSMutableArray array];
        self.totalArray = [NSMutableArray array];
        selectArray = [NSMutableArray array];
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f];
        
    }
    return self;
}
//对情况赋值
- (void)addTitleStrArray {
    CGFloat maxy  =75;
    
    for (int i = 0 ; i < _totalArray.count; i++) {
        UILabel *lab1 = [[UILabel alloc] initWithFrame:CGRectMake(10, maxy, 200, 30)];
        
        FenLeiSelectListModle *modle = _totalArray[i];
        lab1.text = modle.name;
        
        [bgv addSubview:lab1];
        
        maxy = maxy +30+50;
        
    }
    
}

- (void)configureView {
    
    
    UIButton *conmitBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    conmitBtn.frame = CGRectMake(0, kView_Height - 50, kView_Width, 50);
    conmitBtn.backgroundColor = [UIColor orangeColor];
    [conmitBtn setTitle:@"确定" forState:(UIControlStateNormal)];
    [self addSubview:conmitBtn];
    [conmitBtn addTarget:self action:@selector(handleSureBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    CGFloat selfView_height = 90*self.totalArray.count + 65+20 + 50 + 80;
    
    changeHight2 =90*self.totalArray.count + 65+20 + 50 + 80;
    _imageV = [[UIImageView alloc] initWithFrame:CGRectMake(15, kView_Height - selfView_height - 40, 90, 90)];
    [_imageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.imgStr]]];
    [self addSubview:_imageV];
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(kView_Width-40, 10, 30, 30);
    [btn setImage: [UIImage imageNamed:@"sousuo_cha"] forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(handleRemoPopView:) forControlEvents:(UIControlEventTouchUpInside)];
    [bgv addSubview:btn];

                     
    
    
    
    
    _priceLB =[[UILabel alloc] initWithFrame:CGRectMake( CGRectGetMaxX(_imageV.frame)+10, 10,100, 25)];
    _priceLB.textColor = [UIColor redColor];
    _priceLB.text = [NSString stringWithFormat:@"价格¥%@",_priceOne];
    [bgv addSubview:_priceLB];
    
    _guigelb = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(_priceLB.frame), CGRectGetMaxY(_priceLB.frame), 100, 25)];
    _guigelb.textColor = [UIColor blackColor];
    _guigelb.text = @"请选择规格";
    _guigelb.font = kFont15;
    [bgv addSubview:_guigelb];
    
    UIView *spLineV = [[UIView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(_guigelb.frame)+10, kView_Width -30, 1)];
    spLineV.backgroundColor = KShouYeBg;
    [bgv addSubview:spLineV];
    
    
    
    
    for (NSInteger j = 0; j<self.totalArray.count; j++) {
        
        NSMutableArray *tempBtnArray = [NSMutableArray array];
        FenLeiSelectListModle *modle = self.totalArray[j];
        
        CGFloat miny = 85+20+30*j+60*j;
        CGFloat minx = 10;
        CGFloat maxWidth = (kView_Width - (modle.value.count+1)*10)/modle.value.count;
        for (int i = 0; i < modle.value.count; i++) {
            UIButton *btn1 = [UIButton buttonWithType:(UIButtonTypeCustom)];
            
            
            NSString *typeStr = modle.type;
            //            if (typeStr.integerValue == 1) {
            btn1.frame = CGRectMake(minx, miny, maxWidth, 30);
            [btn1 setTitle:modle.value[i] forState:(UIControlStateNormal)];
            //            }else{
            //
            //                maxWidth = (kView_Width - 4*10)/4;
            //                btn1.frame = CGRectMake(minx, miny, maxWidth, 30);
            //                [btn1 setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: modle.value[i]]]] forState:UIControlStateNormal];
            //
            //            }
            
            
            [btn1 setBackgroundImage:[UIImage imageNamed:@"anniu"] forState:(UIControlStateNormal)];
            [btn1 setBackgroundImage:[UIImage imageNamed:@"bg1"] forState:(UIControlStateSelected)];
            [btn1 setBackgroundImage:[UIImage imageNamed:@"xianshimiaosha_di"] forState:UIControlStateDisabled];
            
            btn1.tag = 1000*j+i;
            [btn1 addTarget:self action:@selector(handleSelectArryOenAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [bgv addSubview:btn1];
            minx = minx + maxWidth+10;
            
            [tempBtnArray addObject:btn1];
            
        }
        
        [btnTotalArray addObject:tempBtnArray.mutableCopy];
    }
    
    
    
    
}
-(void)addCountView{
    
    
    
    countView = [[UIView alloc] initWithFrame:CGRectMake(0, kView_Height - 50 - 100, kScreenWidth, 100)];
    [self addSubview:countView];
    
    
    
    UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
    lb.text = @"购买数量";
    lb.textColor = [UIColor blackColor];
    lb.font = [UIFont systemFontOfSize:16];
    [countView addSubview:lb];
    
    
    UIView *spLineV2 = [[UIView alloc] initWithFrame:CGRectMake(15, CGRectGetMinY(lb.frame)-10, kView_Width -30, 1)];
    spLineV2.backgroundColor = KShouYeBg;
    [countView addSubview:spLineV2];
    
    
    if (_totalArray.count==0) {
        spLineV2.hidden = YES;
    }else {
        spLineV2.hidden = NO;
    }
    
    
    UIView *spLineV3 = [[UIView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(lb.frame)+10, kView_Width -30, 1)];
    spLineV3.backgroundColor = KShouYeBg;
    [countView addSubview:spLineV3];
    
    UIButton *bt_add= [UIButton buttonWithType:UIButtonTypeCustom];
    bt_add.frame = CGRectMake(self.frame.size.width-10-40, 10,40, 30);
    [bt_add setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    
    [bt_add setTitleColor:[UIColor blackColor] forState:0];
    bt_add.titleLabel.font = [UIFont systemFontOfSize:20];
    [bt_add setTitle:@"+" forState:0];
    [bt_add addTarget:self action:@selector(handlePayNumAction:) forControlEvents:UIControlEventTouchUpInside];
    bt_add.tag = 202;
    [countView addSubview:bt_add];
    
    tf_count = [[UITextField alloc] initWithFrame:CGRectMake(bt_add.frame.origin.x -45, 10, 40, 30)];
    tf_count.text = _minNum;
    tf_count.textAlignment = NSTextAlignmentCenter;
    tf_count.font = [UIFont systemFontOfSize:15];
    tf_count.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
    tf_count.delegate = self;
    [tf_count addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingDidEnd];
    [countView addSubview:tf_count];
    
    
    UIButton *bt_reduce= [UIButton buttonWithType:UIButtonTypeCustom];
    bt_reduce.frame = CGRectMake(tf_count.frame.origin.x -45, 10, 40, 30);
    [bt_reduce setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    [bt_reduce setTitleColor:[UIColor blackColor] forState:0];
    bt_reduce.titleLabel.font = [UIFont systemFontOfSize:20];
    [bt_reduce setTitle:@"-" forState:0];
    [bt_reduce addTarget:self action:@selector(handlePayNumAction:) forControlEvents:UIControlEventTouchUpInside];
    bt_reduce.tag = 201;
    [countView addSubview:bt_reduce];
    
    
    UILabel *contLB = [[UILabel alloc] initWithFrame:CGRectMake(10,CGRectGetMaxY(bt_reduce.frame)+20, 100, 30)];
    contLB.text = @"总计";
    contLB.font = kFont16;
    [countView addSubview:contLB];
    
    _countMoenyLable = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(bt_reduce.frame), CGRectGetMaxY(bt_reduce.frame)+20, 100, 30)];
    _countMoenyLable.text = [NSString stringWithFormat:@"¥%@", _priceOne];
    _countMoenyLable.textAlignment = NSTextAlignmentRight;
    _countMoenyLable.textColor = [UIColor redColor];
    [countView addSubview:_countMoenyLable];
    
    
    
    
}

//选择的数量
- (void)handlePayNumAction :(UIButton *)sender {
    numPay = [tf_count.text intValue];
    CGFloat money =[_priceOne floatValue];
    if (sender.tag == 201) {
        if (numPay< [_minNum intValue]+1) {
            [self showTextNoActivity:[NSString stringWithFormat:@"起订量 %@",_minNum] timeLength:2];
            return;
        }
        numPay--;
        tf_count.text = [NSString stringWithFormat:@"%ld",numPay];
        
        _countMoenyLable.text = [NSString stringWithFormat:@"¥%.1f", money *numPay];
        
    }
    
    if (sender.tag == 202) {
        numPay++;
        
        if ([_maxNumTemp integerValue] ==0) {//判断是否限购
            if ( numPay >[_maxNum intValue]) {//不限购则小于库存
                [self showTextNoActivity:[NSString stringWithFormat:@"库存仅剩 %@",_maxNum] timeLength:2];
                return;
            }
            
        }
        else {//限购则小于限购数
            
            if ( numPay >[_maxNumTemp intValue]) {//不限购则小于库存
                [self showTextNoActivity:[NSString stringWithFormat:@"该商品限购 %@",_maxNumTemp] timeLength:2];
                return;
            }
        }
       
        tf_count.text = [NSString stringWithFormat:@"%ld",numPay];
        _countMoenyLable.text = [NSString stringWithFormat:@"¥%.1f", money *numPay];
    }
}

//实时获取输入框的值
- (void)textFieldEditChanged:(UITextField *)textF {
    numPay = [textF.text intValue];
    
    CGFloat money =[_priceOne floatValue];
    if ([_maxNumTemp integerValue] == 0) {//判断是否为限购商品，为0 则不限购，
        if (numPay > [_maxNum intValue]) {
            [self showTextNoActivity:[NSString stringWithFormat:@"库存仅剩 %@",_maxNum] timeLength:2];
            numPay =[_maxNum intValue];
            
        }
    }else {//不为0 则不能大于限购数量
        if (numPay > [_maxNumTemp intValue]) {
            [self showTextNoActivity:[NSString stringWithFormat:@"本商品限购 %@",_maxNumTemp] timeLength:2];
            numPay =[_maxNumTemp intValue];
            
        }
    }
    
    
   
    //输入的值不能小于起订量
    if (numPay < [_minNum intValue]) {
        [self showTextNoActivity:[NSString stringWithFormat:@"起订量 %@",_minNum] timeLength:2];
        numPay =[_minNum intValue];
    }
    
    tf_count.text = [NSString stringWithFormat:@"%ld",numPay];
    _countMoenyLable.text = [NSString stringWithFormat:@"¥%.1f", money *numPay];
    
}



//回收视图的代理事件
- (void)handleSureBtnAction :(UIButton *)sender  {
    if(self.delegate && [self.delegate respondsToSelector:@selector(sureThirdViewBtnAction:BackArray:)])
    {
       
        CGFloat money =[_priceOne floatValue];
        NSString *allMoneys = [NSString stringWithFormat:@"%f",money *tf_count.text.integerValue];
        NSArray *backArr = @[_selectModle,tf_count.text,allMoneys];
        [self.delegate sureThirdViewBtnAction:sender BackArray:backArr];
    }
}



// 按钮的点击事件 处理选中btn
- (void)handleSelectArryOenAction:(UIButton *)sender {
    
    NSInteger section = sender.tag/1000;
    NSInteger row = sender.tag%1000;
    
    FenLeiSelectListModle *modle  = self.totalArray[section];
    NSString *string = modle.value[row];
    
    NSString *taaa = selectArray[section];
    
    
    if ([string isEqualToString:taaa]) {
        [selectArray replaceObjectAtIndex:section withObject:@""];
    } else {
        [selectArray replaceObjectAtIndex:section withObject:string];
    }
    
    
    
    
    
    // 处理后续
    [self handleData];
}

// 通过选中的数据  更改视图的样式 (选中 可选 不可选)
-(void)handleData{
    
    // 筛选出哪些可点击
    
    // 可点击的集合
    //    NSMutableSet *tempSet = [[NSMutableSet alloc] init];
    
    NSMutableArray *tempArray = [NSMutableArray array];
    
    for (NSInteger i = 0; i<selectArray.count; i++) {
        
        NSMutableArray *tarray = [NSMutableArray array];
        
        [tempArray addObject:tarray];
        
    }
    
    NSMutableArray *tempbArray = [NSMutableArray array];
    
    for (NSInteger i = 0; i<selectArray.count; i++) {
        
        NSMutableArray *tbarray = [NSMutableArray array];
        
        [tempbArray addObject:tbarray];
        
    }
    
    //遍历
    for (NSInteger i = 0; i<selectArray.count; i++) {
        
        NSString *select = selectArray[i];
        
        for (FenLeiExistListModle *modle in _array4) {
            NSMutableSet *seta = [NSMutableSet setWithArray:modle.sku_key];
            
            NSSet *setb = [NSSet setWithArray:@[select]];
            
            if ([setb isSubsetOfSet:seta] || [select isEqualToString:@""]) {
                
                for (NSInteger j = 0; j<modle.sku_key.count; j++) {
                    if (j!=i){
                        
                        NSMutableArray *tbarray = tempbArray[j];
                        
                        [tbarray addObject:modle.sku_key[j]];
                    }
                }
                
            }
            
        }
        
        for (NSInteger k = 0; k<selectArray.count; k++) {
            if (k!=i){
                
                NSMutableArray *tbarray = tempbArray[k];
                
                NSMutableArray *tarray = tempArray[k];
                
                if (tarray.count == 0) {
                    [tarray addObjectsFromArray:tbarray];
                } else {
                    NSMutableArray *newArray = [NSMutableArray array];
                    
                    for (NSString *strr in tarray) {
                        
                        if ([tbarray containsObject:strr]) {
                            [newArray addObject:strr];
                        }
                    }
                    
                    [tempArray replaceObjectAtIndex:k withObject:newArray];
                }
            }
        }
    }
    
    
    // 更改
    for (NSInteger j = 0; j < self.totalArray.count; j++) {
        
        
        
        FenLeiSelectListModle *modle = self.totalArray[j];
        NSArray *tempBtnArr = btnTotalArray[j];
        
        for (int i = 0; i < modle.value.count; i++) {
            
            
            NSString *string = modle.value[i];
            
            UIButton *btn = tempBtnArr[i];
            
            NSMutableArray *ttt = tempArray[j];
            
            if (self.totalArray.count == 1) {
                if ([selectArray containsObject:string]) {
                    btn.selected = YES;
                    btn.enabled = YES;
                } else {
                    btn.selected = NO;
                    btn.enabled = YES;
                }
            }else {
                if ([selectArray containsObject:string]) {
                    btn.selected = YES;
                    btn.enabled = YES;
                }else if ([ttt containsObject:string]){
                    btn.selected = NO;
                    btn.enabled = YES;
                }else{
                    btn.selected = NO;
                    btn.enabled = NO;
                }
            }
            
            
            
        }
        
    }
    
   
    
    for (FenLeiExistListModle *modle in _array4) {
        
        NSSet *seta = [NSSet setWithArray:modle.sku_key];
        NSSet *setb = [NSSet setWithArray:selectArray];
        if ([seta isEqual:setb]) {
            _selectModle = modle;
            _minNum = modle.minimum;
            //_maxNum = modle.maximum;
            _priceOne = modle.sell_price;
            
            _priceLB.text = [NSString stringWithFormat:@"价格¥%@",_priceOne];
            
            if (_minNum.integerValue > tf_count.text.integerValue) {
                tf_count.text = _minNum;
            }
            
            
            CGFloat money =[_priceOne floatValue];
            _countMoenyLable.text = [NSString stringWithFormat:@"¥%.1f", money *tf_count.text.integerValue];
            
            
        }
    } /**/
    
    
}



//监听键盘的弹出和回收
- (void)keyboardWillShow:(NSNotification*)notification {
    CGRect keyboardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; //获得键盘的rect
    
    //CGRectMake(0, kView_Height - selfView_height, kView_Width, selfView_height)
    bgv.frame = CGRectMake(0,kView_Height - changeHight- keyboardFrame.size.height+100, kView_Width, changeHight);
    
    
    
    countView .frame = CGRectMake(0,kView_Height - 50 - 100- keyboardFrame.size.height+100, kView_Width, 350);
    
    //CGRectMake(15, kView_Height - selfView_height - 40, 90, 90)
    _imageV.frame = CGRectMake(15,kView_Height - changeHight2 - 40-keyboardFrame.size.height+100, 90, 90);
    
}
- (void)keyboardWillHide:(NSNotification*)notification {
    
    bgv.frame = CGRectMake(0, kView_Height - changeHight, kView_Width, changeHight);
    countView .frame =CGRectMake(0, kView_Height - 50 - 100, kScreenWidth, 100);
    _imageV.frame =CGRectMake(15, kView_Height - changeHight - 40, 90, 90);
    
}


//回收视图
- (void)handleRemoPopView:(UIButton *)sender {
    if(self.delegate && [self.delegate respondsToSelector:@selector(remoPopViewBtnAction:)])
    {
        [self.delegate remoPopViewBtnAction:sender];
    }
}

@end
